package com.shixun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shixun.domain.Account;
import com.shixun.domain.Student;
import com.shixun.dto.AccountDto;
import com.shixun.dto.LoginDto;
import com.shixun.exception.exception.DormException;
import com.shixun.mapper.AccountMapper;
import com.shixun.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shixun.service.StudentService;
import com.shixun.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shixun
 * @since 2023-06-10
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    @Autowired
    private StudentService studentService;

    @Override
    public String login(LoginDto loginDto) {
        String sno = loginDto.getSno();
        String password = loginDto.getPassword();
        String s = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        LambdaQueryWrapper<Student> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getSno,sno);
        Student student = studentService.getOne(queryWrapper);
        if (student==null){
            throw new DormException("学号或密码错误");
        }
        Long id = student.getId();
        LambdaQueryWrapper<Account> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(Account::getSid,id);
        Account account = this.getOne(queryWrapper1);
        String password1 = account.getPassword();
        if (!s.equals(password1)){
            throw new DormException("学号或密码错误");
        }
        return sno;
    }

    @Override
    public R updatePassword(AccountDto accountDto,String sno) {
        String oldPassword = accountDto.getOldPassword();
        String newPassword = accountDto.getNewPassword();
        String newPassword2 = accountDto.getNewPassword2();

        //通过学号找出学生id
        LambdaQueryWrapper<Student> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getSno,sno);
        Student student = studentService.getOne(queryWrapper);
        Long id = student.getId();
        Account account = this.getById(id);
        String password = account.getPassword();


        String s1 = DigestUtils.md5DigestAsHex(oldPassword.getBytes(StandardCharsets.UTF_8));
        if (!s1.equals(password)){
            throw new DormException("原密码输入错误，请重试");
        }
        if (!newPassword2.equals(newPassword)){
            throw new DormException("新密码两次输入不一致，请重试");
        }
        //对新密码进行md5加密
        String s2 = DigestUtils.md5DigestAsHex(newPassword.getBytes(StandardCharsets.UTF_8));
        account.setPassword(s2);
        this.updateById(account);
        return new R(1,"修改成功",null);
    }
}
